<script setup lang="ts">
import type { PropType } from 'vue'
import { computed } from 'vue'
import { IconCheckCircleFill, IconExclamationCircleFill } from '@arco-design/web-vue/es/icon'

defineOptions({ name: 'ValidateInput' })

const $props = defineProps({
  modelValue: {
    type: String as PropType<string>,
    default: undefined,
  },
  validator: {
    type: Function as PropType<() => boolean>,
    default: undefined,
  },
})
const $emits = defineEmits(['update:modelValue', 'input'])

const computedValue = computed<string | undefined>({
  get: () => $props.modelValue,
  set: (newValue) => {
    $emits('update:modelValue', newValue)
    $emits('input', newValue)
  },
})

const computedValidateState = computed<boolean>(() => {
  if ($props.validator && typeof $props.validator === 'function') {
    return $props.validator()
  }
  return !!computedValue.value?.length
})
</script>

<template>
  <a-input
    v-model="computedValue"
    v-bind="$attrs"
    :class="computedValidateState ? 'feedback-success' : 'feedback-error'"
  >
    <template #suffix>
      <IconCheckCircleFill v-if="computedValidateState" size="16" />
      <IconExclamationCircleFill v-else size="16" />
    </template>
  </a-input>
</template>

<style lang="scss">
  .feedback-success .arco-input-suffix .arco-icon {
    color: rgb(var(--success-6));
  }
  .feedback-error .arco-input-suffix .arco-icon {
    color: rgb(var(--warning-6));
  }
</style>
